package org.dydl.controller.system;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.BasicErrorController;
import org.springframework.boot.autoconfigure.web.DefaultErrorAttributes;
import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.util.HashMap;
import java.util.Map;

/**
 * 自定义错误控制器
 * 
 * {@link} DefaultHandlerExceptionResolver
 * 
 * 常用异常处理
 * BindException							400 (Bad Request)
 * ConversionNotSupportedException			500 (Internal Server Error)
 * HttpMediaTypeNotAcceptableException		406 (Not Acceptable)
 * HttpMediaTypeNotSupportedException		415 (Unsupported Media Type)
 * HttpMessageNotReadableException			400 (Bad Request)
 * HttpMessageNotWritableException			500 (Internal Server Error)
 * HttpRequestMethodNotSupportedException	405 (Method Not Allowed)
 * MethodArgumentNotValidException			400 (Bad Request)
 * MissingServletRequestParameterException	400 (Bad Request)
 * MissingServletRequestPartException		400 (Bad Request)
 * NoHandlerFoundException					404 (Not Found)
 * NoSuchRequestHandlingMethodException		404 (Not Found)
 * TypeMismatchException					400 (Bad Request)
 * 
 * @author shichao
 */
@Controller //不可缺失
public class MyErrorController extends BasicErrorController implements ErrorController {

    private static final Logger LOGGER = LoggerFactory.getLogger(MyErrorController.class);

    @Autowired
    public MyErrorController(ServerProperties serverProperties) {
        super(new DefaultErrorAttributes(), serverProperties.getError());
    }

    /**
     * 覆盖默认的Json响应
     */
    @Override
    public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
        Map<String, Object> body = getErrorAttributes(request,
                isIncludeStackTrace(request, MediaType.ALL));
        HttpStatus status = getStatus(request);

        LOGGER.error(body.toString());
        HttpSession session = request.getSession();
        session.setAttribute("errorPath", body.get("path"));

        //输出自定义的Json格式
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("success", false);
        map.put("msg", body.get("message"));

        return new ResponseEntity<Map<String, Object>>(map, status);
    }

    /**
     * 覆盖默认的HTML响应
     */
    @Override
    public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {
        response.setStatus(getStatus(request).value());
        String downloadToken = JSON.toJSONString(request.getParameterMap().get("downloadToken"));
        if (downloadToken != null) {
        	Cookie cookie = new Cookie("downloadToken", StringUtils.strip(downloadToken, "[\"\"]"));
        	cookie.setPath("/");
        	response.addCookie(cookie);
        }
//        Map<String, Object> model = getErrorAttributes(request,
//                isIncludeStackTrace(request, MediaType.TEXT_HTML));

        //指定自定义的视图
        return new ModelAndView("redirect:/public/error.html");
    }
}